<template>
  <el-dialog title="请选择" :visible.sync="visible" :width="'500px'" :modal-append-to-body="true" :append-to-body="true" @open="dialogOpen" @close="closeEvent" :lock-scroll="true">
    <el-form v-model="model" :label-width="'150px'">
      <el-form-item label="请选择分组:">
        <el-select filterable v-model="model.group" placeholder="请选择">
          <el-option v-for="item in groups" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="请选择级别:">
        <el-select filterable v-model="model.level" placeholder="请选择">
          <el-option v-for="item in levels" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-button slot="footer" type="primary" size="small" @click="confirm">确认</el-button>
  </el-dialog>
</template>
<script>
  import groupMixin from '@/base/mixin/group';
  import levelMixin from '@/base/mixin/level';
  export default {
    mixins: [groupMixin, levelMixin],
    props: {
      afterChoose: {
        type: Object,
        default() {
          return {};
        }
      }
    },
    data() {
      return {
        model: {
          group: '',
          level: ''
        },
        groups: [],
        levels: [],
        optionChoose: null,
        visible: false
      };
    },
    methods: {
      dialogOpen() {
        this.reset();
        this.$nextTick(r => {
          if (this.groups.length === 0) {
            this.groupOptions();
          }
          if (this.levels.length === 0) {
            this.levelOptions();
          }
        });
      },
      getOption() {
        this.visible = true;
        return new Promise((resolve, reject) => {
          this.optionChoose = {
            resolve: resolve,
            reject: reject
          };
        });
      },
      groupOptions() {
        this.fetchGroup().then(res => {
          res.list.forEach((r, idx) => {
            this.groups.push({
              label: r.name,
              value: r.id
            });
          });
        });
      },
      levelOptions() {
        this.fetchLevel().then(res => {
          res.list.forEach((r, idx) => {
            this.levels.push({
              label: r.name,
              value: r.id
            });
          });
        });
      },
      reset() {
        this.model = {};
      },
      confirm() {
        let postData = { ...this.model };
        this.optionChoose.resolve(postData);
        this.closeEvent(true);
      },
      closeEvent(success) {
        if (!success) {
          this.optionChoose.reject();
        }
        this.visible = false;
      }
    }
  };
</script>